package com.itheima.appserver.Service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.excepiton.ErrorResult;
import com.itheima.appserver.excepiton.MyException;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.utils.FaceDetect;
import com.itheima.commons.utils.UploadPicUtil;
import com.itheima.dubbo.interfaces.UserInfoApi;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
@Service
public class UserInfoService {

    @Reference
    private UserInfoApi userInfoApi;

    public void loginReginfo(Map<String, String> params) {
        //查看参数是否合法
        if (StrUtil.hasBlank(params.get("gender"), params.get("nickname"), params.get("birthday"), params.get("city"))) {
            throw new MyException(ErrorResult.paramesIsEmpty());
        }

        //合法的话，调用dubbo将数据添加到UserInfo
        userInfoApi.addUserInfo(UserInfo.builder()
                .userId(UserThreadLocal.getUserId())
                .nickName(params.get("nickname"))
                .birthday(params.get("birthday"))
                .city(params.get("city"))
                .sex(params.get("gender").equalsIgnoreCase("man") ? 1 : 2)
                .build());

    }

    public void loginReginfoHead(MultipartFile headPhoto) {
        //判断文件格式
        if (!StrUtil.endWithAnyIgnoreCase(headPhoto.getOriginalFilename(), ".png", ".jpg", ".jpeg")) {
            throw new MyException(ErrorResult.photoFormartError());
        }
        System.out.println("day02 图片格式正确");
        //校验文件的大小
        long size = headPhoto.getSize();
        if(size>1024*1024*2){
            throw new MyException(ErrorResult.photoSizeError());
        }
        System.out.println("day02 图片大小正确");
        //校验人*
        try {
            if (!FaceDetect.detectFace(headPhoto.getBytes())) {
                throw new MyException(ErrorResult.photoFormartError());
            }// 上传到阿里云OSS  返回地址
            String pictureURL = UploadPicUtil.uploadPicture(headPhoto.getBytes(),
                    StrUtil.subAfter(headPhoto.getOriginalFilename(), ".", true));
            System.out.println("day02 图片上传阿里成功");
            // 把地址更新到MYSQL数据库
            userInfoApi.updateLogo(UserThreadLocal.getUserId(), pictureURL);

        } catch (IOException e) {
            throw new MyException(ErrorResult.photoSizeError());
        }

    }
}
